package com.tepth.vehiclemaintenance.mvp.work.operator;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.adapter.JobContentAdapter;
import com.tepth.vehiclemaintenance.adapter.TroubleSuggestTypeAdapter;
import com.tepth.vehiclemaintenance.base.BaseBackFragment;
import com.tepth.vehiclemaintenance.bean.ChooseOperator;
import com.tepth.vehiclemaintenance.bean.MaintainDriverRemark;
import com.tepth.vehiclemaintenance.bean.ProcessDecorate;
import com.tepth.vehiclemaintenance.bean.TroubleSuggestSection;
import com.tepth.vehiclemaintenance.bean.TroubleType;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.dataprovider.SuggestListProvider;
import com.tepth.vehiclemaintenance.tools.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by zhangyu on 2017/5/15.
 */

public class OperatorFragment extends BaseBackFragment implements OperatorContract.View {
    private static final String PARAMETER = "ListDriverRemark";

    public static OperatorFragment newInstance(ArrayList<MaintainDriverRemark> list) {
        OperatorFragment fragment = new OperatorFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAMETER, list);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.recycler_view_trouble)
    RecyclerView mRecyclerViewTrouble;
    @BindView(R.id.recycler_view_suggest)
    RecyclerView mRecyclerViewSuggest;
    JobContentAdapter jobContentAdapter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    private OperatorContract.Presenter mPresenter;
    private ArrayList<MaintainDriverRemark> mRemarkList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            ArrayList<MaintainDriverRemark> mMaintainDriverRemarks = (ArrayList<MaintainDriverRemark>) bundle.getSerializable(PARAMETER);
            if (mMaintainDriverRemarks != null) {
                for (MaintainDriverRemark remark : mMaintainDriverRemarks) {
                    if (remark.getDriverRemark() != null && !remark.getDriverRemark().isEmpty()) {
                        mRemarkList.add(remark);
                    }
                }
            }
        }
    }

    @Override
    protected void setPresenter() {
        mPresenter = new OperatorPresenter();
        OperatorContract.Model model = new OperatorModel();
        mPresenter.setVM(this, model);
    }

    @Override
    protected void unbindPresenter() {
        mPresenter.onDestroy();
    }

    @Override
    protected void initView(View view) {
        mToolbar.setTitle("操作建议项");
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_save:
                        pop();
                        break;
                }
                return true;
            }
        });
        initToolbarNav(mToolbar);
        mRecyclerViewTrouble.setLayoutManager(new LinearLayoutManager(_mActivity));
        if (SuggestListProvider.getSuggest() == null) {
            mPresenter.getAllSuggest();
        } else {
            showTroubleClassifications(SuggestListProvider.getSuggest());
        }
    }

    private void makeData() {
//        List<TroubleSuggestSection> sections = new ArrayList<>();
//        if(mMaintainDriverRemarks != null){
//            for(MaintainDriverRemark remark : mMaintainDriverRemarks){
//
//            }
//        }
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_choose_operator, container, false);
    }

    @Override
    public void onNetworkError(String msg) {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onTokenInvalid(String msg) {

    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(_mActivity, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public void showSuggest(ArrayList<ChooseOperator> list) {
        if (list != null)
            showTroubleClassifications(list);
    }

    //记录type选中个数
    private Map<String, Integer> sparseIntArray = new HashMap<>();
    //已选的操作项
    LongSparseArray<ProcessDecorate> mSelectedSuggestArray = new LongSparseArray<>();

    private void showTroubleClassifications(List<ChooseOperator> list) {
        if (mRemarkList == null || mRemarkList.isEmpty()) {
            return;
        }
        if (SuggestListProvider.getSuggest() == null) {
            SuggestListProvider.setSuggest(list);
        }
        for (ChooseOperator chooseOperator : list) {
            for (MaintainDriverRemark driverRemark : mRemarkList) {
                if (driverRemark.getContentTypeCode().equals(chooseOperator.getCode())) {
                    List<ChooseOperator.ListTroubleTypeBean> listTroubleTypeBeen =
                            chooseOperator.getListTroubleType();
                    for (ChooseOperator.ListTroubleTypeBean troubleTypeBean : listTroubleTypeBeen) {
                        if (troubleTypeBean.getName().equals(driverRemark.getDriverRemark())) {
                            driverRemark.setListProcess(troubleTypeBean.getListProcess());
                        }
                    }
                }
            }
        }
        setAdapter(makeTypeData());
    }

    private ArrayList<TroubleSuggestSection> makeTypeData() {
        Map<String, List<TroubleType>> map = new HashMap<>();
        ArrayList<TroubleSuggestSection> sections = new ArrayList<>();
        for (MaintainDriverRemark driverRemark : mRemarkList) {
            String key = driverRemark.getContentTypeName();
            if (map.containsKey(key)) {
                List<TroubleType> list = map.get(key);
                TroubleType troubleType = new TroubleType(driverRemark.getContentTypeCode(),
                        driverRemark.getDriverRemark(),
                        driverRemark.getContentTypeName(),
                        driverRemark.getListProcess());
                list.add(troubleType);
            } else {
                List<TroubleType> list = new ArrayList<>();
                TroubleType troubleType = new TroubleType(driverRemark.getContentTypeCode(),
                        driverRemark.getDriverRemark(),
                        driverRemark.getContentTypeName(),
                        driverRemark.getListProcess());
                list.add(troubleType);
                map.put(key, list);
            }
        }
        for (String key : map.keySet()) {
            TroubleSuggestSection troubleSuggestSectionHead = new TroubleSuggestSection(true, key);
            TroubleSuggestSection troubleSuggestSectionContent = new TroubleSuggestSection(map.get(key));
            sections.add(troubleSuggestSectionHead);
            sections.add(troubleSuggestSectionContent);
        }
        return sections;
    }

    private void setAdapter(ArrayList<TroubleSuggestSection> list) {

        if (list != null) {
            mRecyclerViewTrouble.setLayoutManager(new LinearLayoutManager(_mActivity));
            final TroubleSuggestTypeAdapter typeAdapter = new TroubleSuggestTypeAdapter(_mActivity, R.layout.item_repair_content,
                    R.layout.item_repair_head, list, new TroubleSuggestTypeAdapter.OnTagClickListener() {
                @Override
                public void onTagClick(TroubleType troubleType) {
                    jobContentAdapter.setNewData(troubleType.getListProcess());
                    jobContentAdapter.setTroubleType(troubleType);
                }
            });
            mRecyclerViewTrouble.setAdapter(typeAdapter);
            jobContentAdapter = new JobContentAdapter(_mActivity,
                    R.layout.item_job_content,
                    new ArrayList<ChooseOperator.ListTroubleTypeBean.ListProcessBean>());
            mRecyclerViewSuggest.setLayoutManager(new LinearLayoutManager(_mActivity));
            mRecyclerViewSuggest.setAdapter(jobContentAdapter);
            mRecyclerViewSuggest.addOnItemTouchListener(new OnItemClickListener() {

                @Override
                public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                    ChooseOperator.ListTroubleTypeBean.ListProcessBean process = jobContentAdapter.getItem(position);
                    process.setChecked(!process.isChecked());
                    jobContentAdapter.notifyItemChanged(position);

                    TroubleType troubleType = jobContentAdapter.getTroubleType();
                    String typeCode = troubleType.getContentTypeCode();
                    String driverRemark = troubleType.getDriverRemark();
                    Integer integer = sparseIntArray.get(driverRemark);
                    if (process.isChecked()) {
                        mSelectedSuggestArray.put(process.getId(),
                                new ProcessDecorate(typeCode, driverRemark, process));
                        if (integer != null) {
                            sparseIntArray.put(driverRemark, integer + 1);
                        } else {
                            sparseIntArray.put(driverRemark, 1);
                        }
                    } else {
                        mSelectedSuggestArray.remove(process.getId());
                        sparseIntArray.put(driverRemark, integer - 1);
                    }

                    if (sparseIntArray.get(driverRemark) > 0) {
                        troubleType.setHasSelected(true);
                    } else {
                        troubleType.setHasSelected(false);
                    }
                    typeAdapter.notifyDataSetChanged();
                }
            });
        }
    }
}
